<template>
  <el-form
    label-width="100px"
    :model="skuInfo"
    ref="skuFormRef"
    :rules="skuRules"
  >
    <el-form-item label="SPU名称">
      <span>{{ props.currentSpuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number
        v-model="skuInfo.price"
        class="mx-4"
        style="width: 100%"
        :min="1"
        :max="10"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number
        v-model="skuInfo.weight"
        style="width: 100%"
        class="mx-4"
        :min="1"
        :max="10"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" rows="4" v-model="skuInfo.skuDesc" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(attr, index) in attrList"
          :key="attr.id"
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
        >
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]" @change="clearAttrRules">
              <el-option
                v-for="attrValue in attr.attrValueList"
                :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                :label="attrValue.valueName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(saleAttr, index) in spuSaleAttrList"
          :key="saleAttr.id"
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
        >
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]" @click="clearSaleAttrRules">
              <el-option
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                :label="saleAttrValue.saleAttrValueName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table
        border
        :data="spuImageList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="图片" align="center">
          <template v-slot="{ row, $index }">
            <el-image
              :src="row.imgUrl"
              :alt="row.imgName"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName" align="center" />
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              v-if="row.isDefault === '0'"
              @click="setDefault(row)"
              >设置为默认项</el-button
            >
            <el-button type="success" v-else disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-button type="primary" @click="skuSubmitForm(skuFormRef)">保存</el-button>
      <el-button @click="emits('changeScene', 1)">取消</el-button>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "SkuForm",
};
</script>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from "@/api/product/spu";
import { reqGetAttrListData } from "@/api/product/attr";
import { useCategoryListStore } from "@/stores/categoryList";
import type {FormInstance, FormRules } from "element-plus";
import {ElMessage } from "element-plus";
import { reqSaveSkuInfo } from '@/api/product/sku';

const categoryStore = useCategoryListStore();
const props = defineProps(["currentSpuInfo"]);
const emits = defineEmits(["changeScene"]);


const skuFormRef = ref<FormInstance>()
interface User {
  date: string
  name: string
  address: string
}

// 定义三个变量来存储响应回来的数据
const spuImageList = ref([]);
const spuSaleAttrList = ref([]);
const attrList = ref([]);

// 准备数据
const skuInfo = reactive({
  // spu名称
  skuName: "",
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: "",
  // 默认图片
  skuDefaultImg: "",
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
});

// 书写一个图片的自定义校验
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  if (value.length === 0) {
    callback("至少选择一张图片...");
    return;
  }
  callback(); // 什么参数都不写 表示放行
};
// 定义校验规则
const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: "请输入sku名称", trigger: "blur" },
    { min: 1, max: 10, message: "长度1-10之间", trigger: "blur" },
  ],
  price: [{ required: true, message: "请输入sku价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入sku重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入sku描述", trigger: "blur" }],
  skuAttrValueList: [
    // 平台属性校验规则
    {
      required: true,
      message: "请至少选择一个平台属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuSaleAttrValueList: [
    {
      required: true,
      message: "请至少选择一个销售属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuImageList: [
    { required: true, validator: skuImageListValidate, trigger: "change" },
  ],
});
// 1. 组件挂载完毕就会发请求
onMounted(async () => {
  /* all可以一次性发送多个请求 如果成功则会将返回值按照书写顺序赋值
  有一个失败 则最终结果都是reject 都失败了 整体性比较强
  allSettled 可以一次性发送多个请求 即使有个别的失败也不会影响整体结果
  可以有成功也可以有失败 响应结果还是按照书写顺序赋值 */
  const spuId = props.currentSpuInfo.id;
  const [resSpuImageList, resSpuSaleAttrList, resAttrList] =
    await Promise.allSettled([
      reqGetSpuImageList(spuId),
      reqGetSpuSaleAttrList(spuId),
      reqGetAttrListData({
        category1Id: categoryStore.category1Id as number,
        category2Id: categoryStore.category2Id as number,
        category3Id: categoryStore.category3Id as number,
      }),
    ]);
  // console.log('sku',resSpuImageList,resSpuSaleAttrList,resAttrList);
  // 赋值 先判断是否是成功的返回值
  if (resSpuImageList?.status === "fulfilled") {
    spuImageList.value = resSpuImageList.value.map((item) => {
      return {
        ...item,
        isDefault: "0",
      };
    });
  }
  if (resSpuSaleAttrList?.status === "fulfilled") {
    spuSaleAttrList.value = resSpuSaleAttrList.value;
  }
  if (resAttrList?.status === "fulfilled") {
    attrList.value = resAttrList.value;
  }
});

// 2. 设置默认图片
const setDefault = (row) => {
  // 排他 先将之前的设置为正常 0
  spuImageList.value.forEach((item) => {
    item.isDefault = "0";
  });
  // 再将被单击的设置为默认项 1
  row.isDefault = "1";
  // 保存一下默认图片的地址
  skuInfo.skuDefaultImg = row.imgUrl;
};
// 3. 当选择图片的时候
const handleSelectionChange = (val) => {
  skuInfo.skuImageList = val;
};

// 4. 单击保存按钮的时候 需要将当前skuInfo数据发送给服务器
const skuSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      skuInfo.spuId = props.currentSpuInfo.id
      skuInfo.category3Id = props.currentSpuInfo.category3Id
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map((item) => {
          const [attrId, attrName, valueId, valueName] = item.split(":");
          return {
            attrId,
            attrName,
            valueId,
            valueName,
          };
        });
        skuInfo.skuSaleAttrValueList= skuInfo.skuSaleAttrValueList.filter(Boolean).map(item=>{
          const [saleAttrId,saleAttrName,saleAttrValueId,saleAttrValueName] = item.split(':')
          return {
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName
          }
        })
        await reqSaveSkuInfo(skuInfo)
        ElMessage.success('添加sku数据成功')
        emits('changeScene',1)
    }else{
      console.log('数据添加失败', fields)
    }
  });
};



// 5. 清空平台属性的校验规则
const clearAttrRules=()=>{
  skuFormRef.value?.clearValidate(['skuAttrValueList'])
}
// 5. 清空销售属性的校验规则
const clearSaleAttrRules=()=>{
  skuFormRef.value?.clearValidate(['skuSaleAttrValueList'])
}
</script>

<style>
</style>